<template>
  <a-modal v-bind="$attrs" title="编辑待办中心" centered :width="400" :mask="false" :maskClosable="false" :destroyOnClose="true" @cancel="cancelHandler">
      <a-form-model :model="configForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <!-- <a-form-model-item label="宽">
          <a-input v-model="configForm.width" />
        </a-form-model-item> -->
        <a-form-model-item label="分类">
          <a-tree
            class="portal-draggable-tree"
            :replaceFields="{children:'children', title:'name', key:'id'}"
            v-model="keyArr"
            checkable
            :blockNode="true"
            :default-expanded-keys="expandedKeys"
            draggable
            :tree-data="treeData"
            @dragenter="onDragEnter"
            @drop="onDrop"
            @check="checkTree"
          >
            <a-icon slot="switcherIcon" type="down" />
            <template slot="custom" slot-scope="item">
              <div class="custom-title-box">
                <span class="title">{{item.name}}</span>
                <a-icon type="swap" class="swap-icon" />
              </div>
            </template>
          </a-tree>
        </a-form-model-item>
        <!-- <a-form-model-item label="最大条数">
          <a-input v-model="configForm.num" />
        </a-form-model-item> -->
      </a-form-model>
      <div slot="footer">
        <a-button @click="cancelHandler">取消</a-button>
        <a-button type="primary" @click="okHandler">确认</a-button>
      </div>
    </a-modal>
</template>
<script>
import { setPersonalConfig } from '@/api/devportalApi.js'
// import { listToTree } from '@/utils/util.js'
import clonedeep from 'lodash.clonedeep'
export default {
  name: 'DealtConfigModal',
  props: {
    categroyList: {
      type: Array,
      defualt: () => []
    },
    workSpaceItem: {
      type: Object,
      defualt: () => ({})
    }
  },
  data () {
    return {
      configForm: {
        width: '',
        content: [],
        num: ''
      },
      treeData: [],
      expandedKeys: [],
      keyArr: []
    }
  },
  methods: {
    getTreeAndShow () {
      let data = clonedeep(this.categroyList)
      let resData = data.map(item => {
        if (this.workSpaceItem.personalConfig && this.workSpaceItem.personalConfig.contentSortList.length > 0) {
          let contentSortList = this.workSpaceItem.personalConfig.contentSortList
          let personalItem = contentSortList.find(obj => obj.contentId == item.id)
          if (personalItem) {
            item.rank = personalItem.rank
          }
          item.checked = contentSortList.some(cfgItem => cfgItem.contentId == item.id)
        } else {
          item.checked = true
        }
        item.scopedSlots = {
          title: 'custom'
        }
        // item.checked = true
        return item
      })
      this.keyArr = resData.filter(item => item.checked).map(item => item.id)
      // this.keyArr = resData.map(item => item.id)
      this.expandedKeys = resData.map(item => item.id)
      this.treeData = resData
    },
    onDragEnter(info) {
      // console.log('onDragEnter');
      // console.log(info);
      // expandedKeys 需要受控时设置
      this.expandedKeys = info.expandedKeys
    },
    onDrop(info) {
      // console.log('onDrop');
      // console.log(info);
      if (!info.dropToGap) {
        return this.$message.warning('只能在同级内拖动排序')
      }
      const dropKey = info.node.eventKey;
      const dragKey = info.dragNode.eventKey;
      const dropPos = info.node.pos.split('-');
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
      const loop = (datas, key, callback) => {
        datas.forEach((item, index, arr) => {
          if (item.id === key) {
            return callback(item, index, arr);
          }
          if (item.children) {
            return loop(item.children, key, callback);
          }
        });
      };
      const data = [...this.treeData];
      // Find dragObject
      let dragObj;
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1);
        dragObj = item;
      });
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, item => {
          item.children = item.children || [];
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj);
        });
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, item => {
          item.children = item.children || [];
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj);
        });
      } else {
        let ar;
        let i;
        loop(data, dropKey, (item, index, arr) => {
          ar = arr;
          i = index;
        });
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj);
        } else {
          ar.splice(i + 1, 0, dragObj);
        }
      }
      this.treeData = data;
    },
    checkTree (checkedKeys, e) {
      this.setCheckedStatus(checkedKeys, e.halfCheckedKeys)
    },
    setCheckedStatus (checkedKeys, halfCheckedKeys) {
      console.log(checkedKeys);
      console.log(halfCheckedKeys);
      
      let loopData = (arr) => {
        arr.forEach(item => {
          if (checkedKeys.includes(item.id) || halfCheckedKeys.includes(item.id)) {
            this.$set(item, 'checked', true)
          } else {
            this.$set(item, 'checked', false)
          }
          if (item.children) {
            loopData(item.children)
          }
        })
      }
      loopData(this.treeData)
    },
    cancelHandler () {
      this.$emit('cancel')
    },
    okHandler () {
      // if (!this.configForm.num || !Number(this.configForm.num)) {
      //   return this.$message.warning('请填写大于0的最大条数')
      // }
      let checkedData = []
      let num = 1
      let loopData = (arr) => {
        arr.forEach(item => {
          item.rank = num++
          if (item.checked) {
            checkedData.push({
              name: item.name,
              id: item.id,
              // parentId: item.parentId,
              rank: item.rank
            })
          }
          if (item.children) {
            loopData(item.children)
          }
        })
      }
      loopData(this.treeData)
      // console.log(checkedData)
      if (checkedData.length === 0) {
        this.$message.warning('请选择数据')
        return
      }
      let contentSortList = checkedData.map(item => ({
        contentId: item.id,
        rank: item.rank
      }))
      let { width, moduleId, moduleName, workspaceId, workspaceName } = this.workSpaceItem
      let submitData = {
        contentSortList,
        // num: this.configForm.num,
        width,
        moduleId,
        moduleName,
        workspaceId,
        workspaceName
      }
      // console.log(submitData)
      let method = this.workSpaceItem.personalConfig ? 'put' : 'post'
      if (method === 'put') {
        submitData.objectVersionNumber = this.workSpaceItem.personalConfig.objectVersionNumber
        submitData._token = this.workSpaceItem.personalConfig._token
        submitData.id = this.workSpaceItem.personalConfig.id
      }
      setPersonalConfig(method, submitData).then(res => {
        if (res.status === 200) {
          this.keyArr = []
          this.$emit('ok')
        }
      })
    }
  },
  mounted () {
  },
  watch: {
    '$attrs.visible' (newStatus) {
      if (newStatus) {
        this.getTreeAndShow()
        if (this.workSpaceItem.personalConfig) {
          this.$set(this.configForm, 'num', this.workSpaceItem.personalConfig.num)
        }
      }
    },
    categroyList: {
      handler: function () {
        this.getTreeAndShow()
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="less" scoped>
.portal-draggable-tree {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  /deep/li .ant-tree-node-content-wrapper {
    .custom-title-box {
      .swap-icon {
        color: #5e83ff;
        display: none;
        transform: rotate(90deg);
        float: right;
        margin-top: 2px;
      }
    }
    &:hover {
      .swap-icon {
        display: block;
      }
    }
  }
  /deep/li .ant-tree-node-content-wrapper.ant-tree-node-selected {
    background-color: transparent;
  }
}
</style>